﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body onload="PageLoad()">
<div>
    <textarea id="txtaList" cols="26" rows="12" readonly="readonly"></textarea><br />
    <input id="txtMessage" type="text" />
    <input type="button" value="Send" onclick="SendMessage()" />
</div>

<script type="text/javascript">
    var strTip = "";
    var objWs = null;
    //服务器端要使用框架去实现 如Netty,nodeJs等
    var conUrl = "ws://localhost:15986";
    var socketCreated = false;
    var arrState = new Array("正在建立连接...", "连接成功!",
                             "正在关闭连接...", "连接关闭!",
                             "正在初始化值...", "连接出错!");

    //加载页面时创建WebSocket的实例
    function PageLoad() {
        //检查浏览器是否支持WebSocket
        window.WebSocket = window.WebSocket || window.MozWebSocket;
        if (!window.WebSocket) {
            alert("WebSocket not supported by this browser");
            return;
        }

        if (socketCreated && (objWs.readyState == 0 || objWs.readyState == 1)) {
            objWs.close();
        } else {
            Handle_List(arrState[4]);
            try {
                objWs = new WebSocket(conUrl);
                socketCreated = true;
            } catch (e) {
                Handle_List(e);
                return;
            }
        }
        //添加Socket对象的打开事件
        //readyState:0 Connecting;1 Open;2 Closing;3 Closed
        objWs.onopen = function () {
            Handle_List(arrState[objWs.readyState]);
        }
        //添加Socket对象的接收服务器数据事件
        objWs.onmessage = function (e) {
            Handle_List("系统消息：" + e.data);
        }
        //添加Socket对象的打开事件
        objWs.onclose = function () {
            Handle_List(arrState[objWs.readyState]);
        }
        //添加Socket对象的打开事件
        objWs.onerror = function () {
            Handle_List(arrState[5]);
        }
    }

    //发送消息按钮事件
    function SendMessage() {
        var txtSend = document.getElementById("txtMessage").value;
        if (txtSend.length > 0) {
            objWs.send(txtSend);
            Handle_List("我说：" + txtSend);
            document.getElementById("txtMessage").value = "";
        }
    }

    //显示与服务器交流内容
    function Handle_List(message) {
        strTip += message + '\n';
        document.getElementById('txtaList').value = strTip;
    }

</script>
</body>
</html>
